package com.lxw.report.engine.reportBuilder;

import com.lxw.report.engine.dataModel.column.ColumnTree;
import com.lxw.report.engine.dataModel.column.ColumnTreeNode;
import com.lxw.report.engine.dataModel.report.*;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 横向展示统计列的报表生成类
 *
 * @author lxw
 */
public class ReportBuilderImpl implements ReportBuilder {
    /**
     * 数据集
     */
    private ReportDataSet reportDataSet;
    /**
     * 报表参数
     */
    private ReportParameter reportParameter;
    /**
     * 报表表头
     */
    private  StringBuilder header = new StringBuilder();
    /**
     * 报表数据部分
     */
    private  StringBuilder tableRows = new StringBuilder();
    /**
     * 报表尾部
     */
    private  StringBuilder footer = new StringBuilder();

    public  ReportBuilderImpl(ReportDataSet reportDataSet, final ReportParameter reportParameter) {
        this.reportDataSet = reportDataSet;
        this.reportParameter = reportParameter;
    }

    /**
     * 画表头
     */
    @Override
    public void drawTableHeaderRows() {
        //左侧维度列集合 用来画左侧表头
        final List<ReportColumn> leftDimensionColumnList = this.reportDataSet.getLeftDimensionList();
        //获取上侧维度列与统计列合并的树结构 用来画右侧表头
        final ColumnTree topColumnTree = this.reportDataSet.getTopColumnTree();
        //上侧维度列+统计列总共需要拼接的表格行数
        int rowCount = topColumnTree.getDepth();
        //虚拟列信息
        boolean enableVirtualCol = this.reportParameter.getOptions().getEnableVirtualCol()==null?false:this.reportParameter.getOptions().getEnableVirtualCol();
        List<ReportVirtualConfig> virtualConfigList = this.reportParameter.getOptions().getVirtualConfig()==null?new ArrayList<ReportVirtualConfig>():this.reportParameter.getOptions().getVirtualConfig();
        enableVirtualCol=enableVirtualCol&&virtualConfigList.size()>0;
        if(enableVirtualCol){
            rowCount++;
        }
        final String rowSpan = rowCount > 1 ? String.format(" rowspan=\"%s\"", rowCount) : "";
        this.tableRows.append("<thead>");
        String dimAndLayoutClassName="easyreport-dimAndLayout";
        String statClassName="easyreport-stat";
        // String virtualClassName="easyreport-virtual";
        for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
            //只有一行  则为布局+统计列 则统计列表头视为上侧维度列表头
            if(rowCount==1||rowIndex!=rowCount-1){
                this.tableRows.append("<tr class=\""+dimAndLayoutClassName+"\">");
            }else{
                this.tableRows.append("<tr class=\""+statClassName+"\">");
            }

            if (rowIndex == 0) {
                //如果开启行号  则拼接行号列
                if(this.reportParameter.getOptions().getEnableLineNumber()!=null&&this.reportParameter.getOptions().getEnableLineNumber()){
                    int lineNumberWidth=50;
                    if(this.reportParameter.getOptions().getLineNumberWidth()!=null){
                        lineNumberWidth=this.reportParameter.getOptions().getLineNumberWidth();
                    }
                    this.tableRows.append(String.format("<th %s style=\"text-align:center;width:"+lineNumberWidth+"px\">%s</th>",rowSpan,"序号"));
                }
                for (ReportColumn leftColumn : leftDimensionColumnList) {
                    int width = leftColumn.getSetting().getWidth();
                    this.tableRows.append(String.format("<th title=\"%s\"%s  style=\"width:"+width+"px;text-align:center\">%s</th>",
                            leftColumn.getReportColumnName(), rowSpan, leftColumn.getReportColumnName()));
                }
            }

            //如果有虚拟列,则循环拼接虚拟列
            if(enableVirtualCol&&(rowIndex==rowCount-2)){
                //上一级的节点数
                int parentTreeSize=topColumnTree.getNodesByLevel(rowIndex-1).size();
                parentTreeSize=parentTreeSize==0?1:parentTreeSize;
                for (int i=0;i<parentTreeSize;i++) {
                    for(ReportVirtualConfig virtualConfig:virtualConfigList){
                        int cols=virtualConfig.getStatCols().split(",").length;
                        final String colSpan = cols > 1 ? String.format(" colspan=\"%s\"", cols) : "";
                        this.tableRows.append(String.format("<th title=\"%s\"%s  style=\"text-align:center\">%s</th>",
                                virtualConfig.getVirtualName(), colSpan, virtualConfig.getVirtualName()));
                    }
                }
            }else{
                int actualRowIndex=rowIndex;
                if(enableVirtualCol&&(rowIndex==rowCount-1)){
                    actualRowIndex--;
                }
                for (ColumnTreeNode rightColumn : topColumnTree.getNodesByLevel(actualRowIndex)) {
                    final String colSpan = rightColumn.getSpans() > 1 ? String.format(" colspan=\"%s\"",
                            rightColumn.getSpans())
                            : "";
                    int width = rightColumn.getColumn().getSetting().getWidth();
                    this.tableRows.append(String.format("<th title=\"%s\"%s  style=\"width:" + width + "px;text-align:center\">%s</th>",
                            rightColumn.getValue(), colSpan, rightColumn.getValue()));
                }
            }
            //添加维度合计列
            this.addSumColumn(rowIndex,rowCount);
            this.tableRows.append("</tr>");
        }
        this.tableRows.append("</thead>");
    }

    /**
     * 获取td的样式
     * @param column
     * @return
     */
    public String getTdStyle(ReportColumn column,boolean isFiexCell,boolean isFloatRight){
        String textAlign="";
        //是否强行设置了居右
        if(isFloatRight){
            textAlign = "text-align:right;";
        }else if(column.getSetting().getTextAlign()!=null){
            textAlign = "text-align:"+column.getSetting().getTextAlign().name()+";";
        }
        StringBuilder sb=new StringBuilder();
        sb.append("style=\"");
        sb.append("mso-number-format:\\@;");
        sb.append(textAlign);
        sb.append("\"");
        if(isFiexCell){
            sb.append(" class=\"easyreport-fixed-column\" ");
        }
        return  sb.toString();
    }

    public String getTd(ReportDataCell cell,ReportColumn column,String value){
        return getTd(cell,column,value,false,false);
    }

    public String getTd(ReportDataCell cell,ReportColumn column,String value,boolean isFiexCell,boolean isFloatRight){
        String cellValue=value;
        if(cell!=null&&column!=null&&column.getBindReported()!=null){
            cellValue=cell.getLinkValue();
        }
        StringBuilder sb=new StringBuilder();
        sb.append("<td "+getTdStyle(column,isFiexCell,isFloatRight)+">")
                .append("<label title=\""+value+"\">"+cellValue+"</label>").append("</td>");
        return  sb.toString();

    }

    /**
     * 生成表体左边每一行的单元格
     *
     * @param treeNodePathMap 树中每个节点的path属性为key,treeNode属性为value的map对象
     * @param lastNodePaths   上一个跨行结点的树路径
     * @param rowNode         当前行结点
     * @param isRowSpan       是否跨行(rowspan)
     * @return
     */
    protected String[] drawLeftFixedColumn(final Map<String, ColumnTreeNode> treeNodePathMap,
                                           final String[] lastNodePaths, final ColumnTreeNode rowNode,
                                           final boolean isRowSpan,boolean changeColor) {
        if (isRowSpan) {
            return this.drawLeftRowSpanColumn(treeNodePathMap, lastNodePaths, rowNode,changeColor);
        }

        final String[] paths = StringUtils.splitPreserveAllTokens(rowNode.getPath(),
                this.reportDataSet.getPathSeparator());
        if (paths == null || paths.length == 0) {
            return null;
        }
        final int level = paths.length > 1 ? paths.length - 1 : 1;
        final String[] currNodePaths = new String[level];
        for (int i = 0; i < level; i++) {
            final String currPath = paths[i] + this.reportDataSet.getPathSeparator();
            currNodePaths[i] = (i > 0 ? currNodePaths[i - 1] + currPath : currPath);
            if (lastNodePaths != null && lastNodePaths[i].equals(currNodePaths[i])) {
                continue;
            }
            final ColumnTreeNode treeNode = treeNodePathMap.get(currNodePaths[i]);
            this.tableRows.append(String.format("<td style=\"mso-number-format:\\@;\" class=\"easyreport-fixed-column\">%s</td>", paths[i]));

        }
        return null;
    }

    /**
     * 按层次遍历报表列树中每个结点，然后以结点path为key,treeNode属性为value，生成一个Map对象
     *
     * @param columnTree 报表列树对象
     * @return 树中每个节点的path属性为key, treeNode属性为value的map对象
     */
    protected Map<String, ColumnTreeNode> getTreeNodePathMap(ColumnTree columnTree) {
        Map<String, ColumnTreeNode> treeNodePathMap = new HashMap<>();
        for (int level = 0; level < columnTree.getDepth(); level++) {
            for (ColumnTreeNode treeNode : columnTree.getNodesByLevel(level)) {
                treeNodePathMap.put(treeNode.getPath(), treeNode);
            }
        }
        return treeNodePathMap;
    }

    /**
     * 生成表体左边每一行的跨行(rowspan)单元格
     *
     * @param treeNodePathMap 树中每个节点的path属性为key,treeNode属性为value的map对象
     * @param lastNodePaths   上一个跨行结点的树路径
     * @param rowNode         当前行结点
     * @return 当前跨行结点的树路径
     */
    protected String[] drawLeftRowSpanColumn(final Map<String, ColumnTreeNode> treeNodePathMap, String[] lastNodePaths,
                                             final ColumnTreeNode rowNode,boolean changeColor) {
        final String[] paths = StringUtils.splitPreserveAllTokens(rowNode.getPath(),
                this.reportDataSet.getPathSeparator());
        if (paths == null || paths.length == 0) {
            return null;
        }

        final int level = paths.length > 1 ? paths.length - 1 : 1;
        final String[] currNodePaths = new String[level];
        for (int i = 0; i < level; i++) {
            final String currPath = paths[i] + this.reportDataSet.getPathSeparator();
            currNodePaths[i] = (i > 0 ? currNodePaths[i - 1] + currPath : currPath);
            if (lastNodePaths != null && lastNodePaths[i].equals(currNodePaths[i])) {
                continue;
            }
            final ColumnTreeNode treeNode = treeNodePathMap.get(currNodePaths[i]);
            if (treeNode == null) {
                this.tableRows.append("<td style=\"mso-number-format:\\@;\" class=\"easyreport-fixed-column\"></td>");
            } else {
                int rowSpan = getRowSpan(treeNode,level,i);
                final String rowspan = rowSpan > 1 ? String.format(" rowspan=\"%s\"", rowSpan)
                        : "";
                this.tableRows.append(
                        String.format("<td style=\"mso-number-format:\\@;\" class=\"easyreport-fixed-column\" %s>%s</td>", rowspan, treeNode.getValue()));
            }
        }
        lastNodePaths = currNodePaths;
        return lastNodePaths;
    }


    @Override
    public void drawTableBodyRows() {
        //左侧维度列节点树结构
        final ColumnTree leftDimensionColumnTree = this.reportDataSet.getLeftDimensionColumnTree();
        //左侧维度列最外侧节点集合
        final List<ColumnTreeNode> lastLevelLeftDimensionNodes = leftDimensionColumnTree.getLastLevelNodes();
        //上侧维度列最外侧节点集合
        final List<ColumnTreeNode> lastLevelTopDimensionNodes = this.reportDataSet.getTopDimensionColumnTree().getLastLevelNodes();
        //所有数据的map存储  key->左侧维度列与上侧维度列加上分割符拼接而成的key  value->改行dataRow对象
        final Map<String, ReportDataRow> dimensionAndRowMap = this.reportDataSet.getDimensionKeyAndRowMap();
        // 统计列
        final List<ReportColumn> statColumns =new ArrayList<>();
        statColumns.addAll(this.reportDataSet.getRealStatisticalList());
        statColumns.addAll(this.reportDataSet.getComputeStatisticalList());

        //每一层级节点的 path 对应的 node (可能会有覆盖情况,因为不是最外层)
        Map<String, ColumnTreeNode> treeNodePathMap = this.getTreeNodePathMap(leftDimensionColumnTree);
        int rowIndex = 0;
        String[] lastNodePaths = null;
        this.tableRows.append("<tbody>");
        //是否要在底部增加统计合计行,即是否有统计列被设置成了按上侧维度列合计
        boolean isTopdimensionSum=statColumns.stream().anyMatch(p->p.getTopDimensionSumed());
        //存储各个需要合计的列 的sum值
        HashMap<String, BigDecimal> footValues=new HashMap<>();
        //存储各个需要小计的列 的sum值。每一个分组之后需要清空
        HashMap<String,BigDecimal> extensionsValues=new HashMap<>();
        //是否需要小计
        boolean isExtensions=statColumns.stream().anyMatch(p->p.getSubTopDimensionSumed());

        if(isExtensions&&reportParameter.getOptions().getMergeSamed()){
            restSpan(leftDimensionColumnTree);
        }
        String lastGroupKey="";//标记当前分组，如果跳到下一个分组了，则增加小计行

        //行号
        int beginIndex=0;
        boolean enableLineNumber=this.reportParameter.getOptions().getEnableLineNumber()==null?false:this.reportParameter.getOptions().getEnableLineNumber();
        if(enableLineNumber){
            beginIndex=(this.reportDataSet.getPageNumber()-1)*this.reportDataSet.getPageSize();
        }
        //遍历行数据
        for (final ColumnTreeNode rowNode : lastLevelLeftDimensionNodes) {
            //如果需要小计
            if(isExtensions){
                //如果是该组最后一个需要额外增加小计行
                String currentGroupKey=getGroupKeyByPath(rowNode.getPath());
                if(!lastGroupKey.equals("") && !currentGroupKey.equals(lastGroupKey)){
                    //画一行小计
                    drawExtensionRow(extensionsValues,leftDimensionColumnTree,statColumns);
                    //清除
                    extensionsValues.clear();
                }
                lastGroupKey=currentGroupKey;
            }
            HashMap<String,BigDecimal> weiduSum=new HashMap<>();

            //增加tr，偶数行需要增加样式
            this.tableRows.append("<tr").append(rowIndex % 2 == 0 ? " class=\"easyreport-row\"" : "").append(">");

            //行号拼接
            if(enableLineNumber){
                beginIndex++;
                this.tableRows.append(String.format("<td style=\"mso-number-format:\\@;\" class=\"easyreport-fixed-column\">%s</td>", beginIndex));
            }
            lastNodePaths = this.drawLeftFixedColumn(treeNodePathMap, lastNodePaths, rowNode,
                this.reportParameter.getOptions().getMergeSamed(),false);
            for (final ColumnTreeNode columnNode : lastLevelTopDimensionNodes) {
                //获取到该行的key
                final String rowKey = this.reportDataSet.getRowKey(rowNode, columnNode);
                //根据key获取到该行的数值类型的数据
                ReportDataRow statRow = dimensionAndRowMap.get(rowKey);
                if (statRow == null) {
                    statRow = new ReportDataRow();
                }
                //遍历所有的数值列，根据列生成该行的td
                for (ReportColumn statColumn : statColumns) {
                    //从该行的数据根据列名获取到该行的单元格
                    ReportDataCell cell = statRow.getCell(statColumn.getSqlColumnName());
                    //获取单元格的值
                    String value = (cell == null) ? "" : cell.toString();
                    //添加一个td
                    this.tableRows.append(getTd(cell,statColumn,value));
                    //如果该列参与统计列合计
                    if(statColumn.getTopDimensionSumed()){
                        this.sumValue(footValues,columnNode.getPath()+ statColumn.getSqlColumnName(),value);
                    }
                    ////如果该列参与统计列小计计
                    if(statColumn.getSubTopDimensionSumed()){
                        this.sumValue(extensionsValues,statColumn.getSqlColumnName(),value);
                    }
                    //如果需要左侧维度列合计,并且该列参与左侧维度列合计
                    if (statColumn.getLeftDimensionSumed()) {
                        //获取columnkey。
                        //获取当前列的维度统计值，然后加入
                        this.weiduSum(weiduSum, statColumn.getSqlColumnName(), value);
                        //如果需要统计列合计，则需要再增加一个合计列的值
                        if (isTopdimensionSum) {
                            this.sumValue(footValues, "合计$" + statColumn.getSqlColumnName(), value);
                        }
                    }
                }
            }
                //遍历各统计列的值，每一个参与维度合计的统计列产生一个td
                List<ReportColumn> statColumnsFooting = statColumns.stream().filter(p->p.getLeftDimensionSumed()).collect(Collectors.toList());
                for (final ReportColumn statColumn : statColumnsFooting) {
                    //TODO 优化格式化
                    //String value = CellFormatUtil.cellFormat(statColumn.getMetaData().getFormat(),weiduSum.get(statColumn.getName()).toString());
                    //String td = getTd(null,statColumn,value);
                    //this.tableRows.append(td);
                }
            this.tableRows.append("</tr>");
            rowIndex++;
        }
        if(isExtensions&&lastLevelLeftDimensionNodes.size()>0){
            //画一行小计
            drawExtensionRow(extensionsValues,leftDimensionColumnTree,statColumns);
        }

        //整体报表画完后,画底部统计列合计
        if(isTopdimensionSum){
            this.drawFootRow(footValues,leftDimensionColumnTree,statColumns,lastLevelTopDimensionNodes);
        }
        this.tableRows.append("</tbody>");
    }

    private void weiduSum(HashMap<String,BigDecimal> weiduSum,String columnKey,String value){
        BigDecimal tempWeiduWum = weiduSum.get(columnKey);
        if(tempWeiduWum==null){
            tempWeiduWum=new BigDecimal(0);
        }
        try{
            BigDecimal a=new BigDecimal(value.replaceAll(",", ""));
            tempWeiduWum = tempWeiduWum.add(a);
        }catch (Exception e){
            tempWeiduWum = tempWeiduWum.add(new BigDecimal(0));
        }
        weiduSum.put(columnKey,tempWeiduWum);
    }

    private String getGroupKeyByPath(String path){
        final String[] paths = StringUtils.splitPreserveAllTokens(path,
                this.reportDataSet.getPathSeparator());
        if (paths == null || paths.length == 0) {
            return null;
        }
        String groupKey="";
        for(int i=0;i<paths.length-2;i++){
            groupKey+=paths[i];
            groupKey+=this.reportDataSet.getPathSeparator();
        }
        return groupKey;
    }

    /**
     * 计算合计值
     */
    private void sumValue(HashMap<String, BigDecimal> sumValues,String columnName,String columnValue){
        //把value加起来
        BigDecimal oldValue= sumValues.get(columnName);
        if(oldValue==null){
            oldValue=new BigDecimal(0);
        }
        try{
            BigDecimal a=new BigDecimal(columnValue.replaceAll(",", ""));
            oldValue = oldValue.add(a);
        }catch (Exception e){
            oldValue = oldValue.add(new BigDecimal(0));
        }
        sumValues.put(columnName,oldValue);
    }

    private void drawExtensionRow(HashMap<String, BigDecimal> extensionsValues,ColumnTree leftFixedColumnTree,List<ReportColumn> statColumns){
        this.tableRows.append("<tr>");
        //先画左侧的小计
        int leftColumnCount = leftFixedColumnTree.getDepth();
        for(int i=0;i<leftColumnCount;i++){
            if (this.reportParameter.getOptions().getEnableLineNumber()==true){
                if(i==leftColumnCount-1){
                    this.tableRows.append(String.format("<td class=\"easyreport-fixed-column\"  style=\"text-align:center\">%s</td>", "小计："));
                }
            }else {
                if(i==leftColumnCount-1){
                    this.tableRows.append(String.format("<td class=\"easyreport-fixed-column\">%s</td>", "小计："));
                }
                else if(!reportParameter.getOptions().getMergeSamed()){
                    this.tableRows.append(String.format("<td class=\"easyreport-fixed-column\">%s</td>", ""));
                }
            }
        }

        //再画右侧的数据
        for(int i=0;i<statColumns.size();i++){
            BigDecimal footValue=extensionsValues.get(statColumns.get(i).getSqlColumnName());
            //TODO 优化
            //String value = CellFormatUtil.cellFormat(statColumns.get(i).getMetaData().getFormat(),footValue);
            //this.tableRows.append(getTd(null,statColumns.get(i).getMetaData(),value));
        }
        this.tableRows.append("</tr>");
    }

    //如果数值列需要合计，则在最后需要添加合计列
    private void drawFootRow( HashMap<String, BigDecimal> footValues,ColumnTree leftFixedColumnTree,List<ReportColumn> statColumns, List<ColumnTreeNode> columnNodes ){
        this.tableRows.append("<tr>");
        //先画左侧的合计,如果显示行号,则合计增加一列合并
        int leftColumnCount = leftFixedColumnTree.getDepth();
        if(this.reportParameter.getOptions().getEnableLineNumber()!=null&&this.reportParameter.getOptions().getEnableLineNumber()){
            leftColumnCount++;
        }
        this.tableRows.append(String.format("<td class=\"easyreport-fixed-column\"  colspan="+leftColumnCount+" >%s</td>", "合计："));
        final ColumnTree rightColumnTree = this.reportDataSet.getTopColumnTree();
        final int rowCount = rightColumnTree.getDepth();
        //如果头部有多行
        if(rowCount>1){
            for(int i=0;i<columnNodes.size();i++){
                ColumnTreeNode columnTreeNode=columnNodes.get(i);
                if(columnTreeNode.getChildren().size()>0){
                    for(int j=0;j<columnTreeNode.getChildren().size();j++){
                        ColumnTreeNode child = columnTreeNode.getChildren().get(j);
                        BigDecimal footValue=footValues.get(columnTreeNode.getPath()+child.getColumn().getSqlColumnName());
                        //TODO 优化格式化
                        //String value = CellFormatUtil.cellFormat(child.getColumn().getMetaData().getFormat(),footValue);
                        //this.tableRows.append(getTd(null,child.getColumn().getMetaData(), value));
                    }
                }else {
                    BigDecimal footValue=footValues.get(columnTreeNode.getColumn().getSqlColumnName());
                    //TODO 优化格式化
                    //String value = CellFormatUtils.cellFormat(columnTreeNode.getColumn().getMetaData().getFormat(),footValue);
                    //this.tableRows.append(getTd(null,columnTreeNode.getColumn().getMetaData(), value));
                }
            }
        }else {
            for(int i=0;i<statColumns.size();i++){
                BigDecimal footValue=footValues.get(statColumns.get(i).getSqlColumnName());
                //优化格式化
                //String value = CellFormatUtils.cellFormat(statColumns.get(i).getMetaData().getFormat(),footValue);
                //this.tableRows.append(getTd(null,statColumns.get(i).getMetaData(),value));
            }
        }

        //如果左侧维度列合计，则需要再最后补合计单元格
        if(rowCount==2){
            for(int i=0;i<statColumns.size();i++){
                //如果该列参加维度合计
                if(statColumns.get(i).getLeftDimensionSumed()){
                    BigDecimal footValue= footValues.get("合计$"+statColumns.get(i).getSqlColumnName());
                    //TODO 优化格式化
                    //String value = CellFormatUtil.cellFormat(statColumns.get(i).getMetaData().getFormat(),footValue);
                    //this.tableRows.append(getTd(null,statColumns.get(i).getMetaData(), value));
                }
            }
        }else {
            //对于多于一个节点的维度深度,暂不考虑
        }
        this.tableRows.append("</tr>");
    }

    /**
     * 添加合计列
     */

    public void addSumColumn(int rowIndex,int rowCount){
        List<ReportColumn> statReportColumnList=new ArrayList<>();
        statReportColumnList.addAll(this.reportDataSet.getRealStatisticalList());
        statReportColumnList.addAll(this.reportDataSet.getComputeStatisticalList());
        //找出参与左侧维度合计的列
        List<ReportColumn> statColumns = statReportColumnList.stream().filter(p->p.getLeftDimensionSumed()).collect(Collectors.toList());
        //如果没有参与左侧维度合计的列，则返回
        if(statColumns.size()==0){
            return;
        }
        final String rowSpan = rowCount > 1 ? String.format(" rowspan=\"%s\"", rowCount) : "";
        if (rowIndex == 0) {
            for (ReportColumn dataColumn : statColumns) {
                int width =100;
                if(dataColumn.getLeftDimensionSumSetting().getWidth()!=null){
                    width=dataColumn.getLeftDimensionSumSetting().getWidth();
                }
                this.tableRows.append(String.format("<th %s  style=\"width:"+width+"px;text-align:center\">%s</th>",
                        rowSpan, dataColumn.getLeftDimensionSumName()));
                }
        }
    }
    @Override
    public void drawTableFooterRows() {

    }

    //如果有小计，则需要重新计算rowspan。
    public int getRowSpan(ColumnTreeNode treeNode,int level,int i){
        int nodeSpan = treeNode.getSpans();
        return nodeSpan;
    }

    public void restSpan(final ColumnTree leftFixedColumnTree){
        if(leftFixedColumnTree.getDepth()>1){
            //目前只对应深度为2的场景。
            if(leftFixedColumnTree.getDepth()==2){
                List<ColumnTreeNode>  roots = leftFixedColumnTree.getRoots();
                for(int i=0;i<roots.size();i++){
                    roots.get(i).setSpans(roots.get(i).getSpans()+1);
                }
            }

        }
    }

    /**
     * 获取ReportTable对象
     * @return
     */
    @Override
    public ReportTable getTable() {
        StringBuilder table = new StringBuilder();
        table.append(this.header.toString());
        table.append("<table border=\"1\" id=\"easyreport\" class=\"easyreport\">");
        table.append(this.tableRows.toString());
        table.append("</table>");
        table.append(this.footer.toString());
        return new ReportTable(table.toString(),this.reportParameter.getSqlText(),this.reportDataSet.getTotalCount());
    }

}
